package com.glory.wxmemsicpda.activity

import android.os.Handler
import android.text.TextUtils
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.glory.wxmemsicpda.R
import com.glory.wxmemsicpda.adapter.MaterialsAdapter
import com.glory.wxmemsicpda.adapter.PageInfoAdapter
import com.glory.wxmemsicpda.base.App.Companion.app
import com.glory.wxmemsicpda.base.BaseDialogActivity
import com.glory.wxmemsicpda.bean.StartLotBean
import com.glory.wxmemsicpda.bean.net.BaseResponseBean
import com.glory.wxmemsicpda.databinding.ActivityWorkBeginBinding
import com.glory.wxmemsicpda.utils.FileUtils
import com.glory.wxmemsicpda.utils.MyUtils
import com.glory.wxmemsicpda.utils.NetUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.Response
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_SimpleDialogEntityCallBack
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils
import kotlinx.android.synthetic.main.activity_work_begin.*
import org.json.JSONObject

class WorkBeginActivity : BaseDialogActivity(), View.OnClickListener {
    private var eqpId: String = ""
    private var lotId: String = ""
    private var testLotId: String = ""
    private var pageInfoList: MutableList<StartLotBean.PRODUCTLISTBean> = mutableListOf()
    private var pageInfoAdapter: PageInfoAdapter = PageInfoAdapter(pageInfoList)
    private var materialsList: MutableList<StartLotBean.MESMATLISTBean> = mutableListOf()
    private var materialsAdapter: MaterialsAdapter = MaterialsAdapter(materialsList)
    private var viewDataBinding: ActivityWorkBeginBinding? = null

    private var tipDialog: FreeUI_GeneralFragmentDialog? = null
    private var testTypeList: MutableList<String> = mutableListOf()
    private var testTimeList: MutableList<String> = mutableListOf()
    private var mTestTypePop: FreeUI_GeneralPop? = null
    private var mTestTimePop: FreeUI_GeneralPop? = null
    private var sTestType = ""
    private var sTestTime = ""


    override fun getLayoutResId(): Int {
        return 0
    }

    override fun initView() {
        viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_work_begin)
        setTitle("批次开始作业")
        freeUI_titleView.setRightListener("开始作业") {
            requestStart()
        }
        eqpId = intent.getStringExtra("showPlugin")!!


        rvInfoList.layoutManager = LinearLayoutManager(this)
        rvInfoList.adapter = pageInfoAdapter

        rvMaterials.layoutManager = LinearLayoutManager(this)
        rvMaterials.adapter = materialsAdapter

//        llEqpMaterials.setOnClickListener(this)
        flTestType.setOnClickListener(this)
        flTestTime.setOnClickListener(this)
        requestData("")

//        llTestLotId.visibility = View.VISIBLE
//        etTestLotId.isFocusable = false
        etLotId.requestFocus()
//        etLotId.isFocusable = true
//        etLotId.isFocusableInTouchMode = true

    }

    private fun requestStart() {
//        val ss = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"c5e5e318389d4c39b914e4c10ba519d4\",\"RESULT\":\"FAIL\",\"RESULTCODE\":null,\"RESULTMESSAGE\":\"请确认批次/设备是否输入！\"},\"Body\":null}}";
//        val dd : BaseResponseBean<*> = Gson().fromJson(ss,object : TypeToken<BaseResponseBean<*>>(){}.type)
//        if (dd!!.isSuccess(true, supportFragmentManager)) {
//            showToast("批次开始成功", true)
//            finish()
//        }
        val map = JsonObject()
        map.addProperty("EQP_ID", eqpId)
        if (etTestLotId.text.toString().isEmpty()){
            map.addProperty("LOT_ID", lotId)
        }else{
            map.addProperty("LOT_ID", lotId+","+etTestLotId.text.toString())
        }
        NetUtils.requestPosNet(this,
            "PDALotStart", "PDALotStart",
            map,
            object : FreeUI_SimpleDialogEntityCallBack<BaseResponseBean<*>?>(this) {
                override fun onSuccess(response: Response<BaseResponseBean<*>?>) {
                    super.onSuccess(response)
                    if (response.body()!!.isSuccess(false, supportFragmentManager)) {
//                        showToast("批次开始成功", true)
                        showMessageDialog(
                            response.body()!!.response.header.resultmessage,
                            supportFragmentManager
                        )
//                        finish()
                    }
                }

                override fun onError(response: Response<BaseResponseBean<*>?>) {
                    super.onError(response)
                    loadError(response.exception, "PDALotStart")
                }
            })
    }

    override fun initData() {
        MyUtils.setEditTextListener(etLotId, this) {
            lotId = it
            if (llTestLotId.visibility == View.GONE) {
                requestData(lotId)
            } else {
                combineLot(it)
            }
        }

        MyUtils.setEditTextListener(etTestLotId, this) {
            testLotId = it

            combineLot(it)

        }

        //获取本地Json数据
        val resultSetData = FileUtils.readJson(this, "test_eqp_info.txt")
        if (resultSetData.status === 0) {
            val sShortcutJson: String = resultSetData.getData().toString()
            if (!TextUtils.isEmpty(sShortcutJson)) {
                //解析JSON
                val jsonObject = JSONObject(sShortcutJson)
                val sTestType = jsonObject.getString("TESTTYPE")
                val sTestTime = jsonObject.getString("TestTime")
                val type = object :TypeToken<MutableList<String>>(){}.type
                testTypeList = Gson().fromJson<MutableList<String>>(sTestType, type)
                testTimeList = Gson().fromJson<MutableList<String>>(sTestTime, type)
            } else {
                showToast(resultSetData.msg, false)
            }
        }
    }

    private fun combineLot(sLotId : String) {
        if (lotId != "" && testLotId != "") {
            requestData("$lotId,$testLotId")
        } else if (lotId == "" && testLotId != "") {
            if (sLotId != ""){
                etLotId.requestFocus()
            }
        } else if (lotId != "" && testLotId == "") {

        }
    }

    private fun requestData(lotId: String) {
//        var ss = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"c5e5e318389d4c39b914e4c10ba519d4\",\"RESULT\":\"SUCCESS\",\"RESULTCODE\":null,\"RESULTMESSAGE\":null},\"Body\":{\"LOT_ID\":\"\",\"EQP_ID\":\"MO-001\",\"EQP_RUN_STATE\":\"闲置中\",\"TRANSID\":\"0\",\"PRODUCT_LIST\":[{\"PNAME\":\"产品型号\",\"PVALUE\":\"\"},{\"PNAME\":\"数量\",\"PVALUE\":\"\"},{\"PNAME\":\"Recipe名称\",\"PVALUE\":\"\"}],\"MES_MAT_LIST\":[]}}}"
//        var dd : BaseResponseBean<StartLotBean> = Gson().fromJson(ss,object : TypeToken<BaseResponseBean<StartLotBean>>(){}.type)
//        if (dd!!.isSuccess(true, supportFragmentManager)) {
//            pageInfoList.clear()
//            materialsList.clear()
//            if (dd!!.response.body!!.producT_LIST.size > 0) {
//                pageInfoList.addAll(dd!!.response.body!!.producT_LIST)
//            }
//            if (dd!!.response.body!!.meS_MAT_LIST.size > 0) {
//                materialsList.addAll(dd!!.response.body!!.meS_MAT_LIST)
//            }
//            pageInfoAdapter.notifyDataSetChanged()
//            materialsAdapter.notifyDataSetChanged()
//            viewDataBinding?.entity = dd.response.body
//
//        }
        val map = JsonObject()
        map.addProperty("EQP_ID", eqpId)
        map.addProperty("LOT_ID", lotId)
        map.addProperty("TESTTYPE", sTestType)
        map.addProperty("TESTCOUNT", sTestTime)
        NetUtils.requestPosNet(this,
            "PDALotStartInfo", "PDALotStartInfo",
            map,
            object : FreeUI_SimpleDialogEntityCallBack<BaseResponseBean<StartLotBean?>?>(this) {
                override fun onSuccess(response: Response<BaseResponseBean<StartLotBean?>?>) {
                    super.onSuccess(response)
                    if (response.body()!!.response.getHeader().getRESULT().toUpperCase() == "SUCCESS") {
                        pageInfoList.clear()
                        materialsList.clear()
                        if (response.body()!!.response.body!!.producT_LIST.size > 0) {
                            pageInfoList.addAll(response.body()!!.response.body!!.producT_LIST)
                        }
                        if (response.body()!!.response.body!!.meS_MAT_LIST.size > 0) {
                            materialsList.addAll(response.body()!!.response.body!!.meS_MAT_LIST)
                        }
                        pageInfoAdapter.notifyDataSetChanged()
                        materialsAdapter.notifyDataSetChanged()
                        viewDataBinding?.entity = response.body()!!.response.body
                        //判断是否要显示第二个lot扫描框
                        if (response.body()!!.response.body!!.morE_LOT == "YES") {
                            llTestLotId.visibility = View.VISIBLE
                        }
//                        if (response.body()!!.response.body!!.eqP_TYPE == "DISCODFD6341") {
//                            llTest.visibility = View.GONE
//                        }else{
//                            llTest.visibility = View.VISIBLE
//                        }

                    }else{
                        tipDialog = FreeApi_DialogUtils.getConfirmDialog(
                            app, "确定", response.body()!!.response.getHeader().getRESULTMESSAGE()
                        ) {
                            finish()
                        }
                        tipDialog!!.show(supportFragmentManager, "DIALOG")
                    }
                }

                override fun onError(response: Response<BaseResponseBean<StartLotBean?>?>) {
                    super.onError(response)
                    loadError(response.exception, "PDALotStartInfo")
                    Handler().postDelayed({ finish() }, 2000)
                }
            })
    }

    //消息提示框
    private fun showMessageDialog(message: String, fragmentManager: FragmentManager) {
        FreeApi_DialogUtils.getConfirmDialog(
            app, "确定", message
        ) {
            finish()
        }.show(fragmentManager, "DIALOG")

    }

    override fun getBaseEntity(): FreeUI_AddViewEntity {
        return FreeUI_AddViewEntity("header", llMain)
    }

    override fun onClick(p0: View?) {
        when (p0!!.id) {
//            R.id.llEqpMaterials -> {
//                FreeApi_Utils.skipWithExtraIntent(
//                    eqpId,
//                    this,
//                    MaterialsListActivity::class.java
//                )
//
//            }
            R.id.flTestType ->{

                if (mTestTypePop != null) {
                    if (mTestTypePop!!.isShowing) {
                        mTestTypePop!!.dismiss()
                    }
                } else {
                    mTestTypePop = FreeApi_PopUtils.getNormalPop(
                        applicationContext, flTestType.width, testTypeList, ivTestType
                    ) { codeS: String?, i: Int ->
                        tvTestType.text = codeS
                        sTestType = codeS!!
                    }
                }
                FreeApi_PopUtils.setArrowShow(ivTestType)
                mTestTypePop!!.showAsDropDown(flTestType, 0, 0)
            }

            R.id.flTestTime -> {

                if (mTestTimePop != null) {
                    if (mTestTimePop!!.isShowing) {
                        mTestTimePop!!.dismiss()
                    }
                } else {
                    mTestTimePop = FreeApi_PopUtils.getNormalPop(
                        applicationContext, flTestTime.width, testTimeList, ivTestTime
                    ) { codeS: String?, i: Int ->
                        tvTestTime.text = codeS
                        sTestTime = codeS!!
                    }
                }
                FreeApi_PopUtils.setArrowShow(ivTestTime)
                mTestTimePop!!.showAsDropDown(flTestTime, 0, 0)
            }

            }
        }
    }
